<template>
  <div class="main" ref="mainContainer">
    <div class="header" ref="headerContainer">
      <div class="header-actions">
        <el-form
          hide-required-asterisk
          class="search-form"
          :model="formData"
          :rules="rules"
          ref="formDataRef"
          label-width="80px"
          @submit.prevent
        >
          <!--input输入-->
          <el-form-item label="用户昵称" prop="nickNameFuzzy">
            <el-input
              clearable
              placeholder="请输入用户昵称"
              v-model.trim="formData.nickNameFuzzy"
            ></el-input>
          </el-form-item>
          <!-- 下拉框 -->
          <el-form-item label="状态" prop="Userstatus">
            <el-select
              class="select"
              clearable
              placeholder="请选择状态"
              v-model="formData.Userstatus"
            >
              <el-option value="1" label="启用"></el-option>
              <el-option value="2" label="禁用"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="file-list">
      <MyTable
        ref="tableRef"
        :dataSource="tableData"
        :columns="columns"
        :fetch="loadDataList"
        :initFetch="true"
        :options="tableOptions"
        @rowSelected="rowSelected"
        @rowdbselected="rowdbselected"
      >
        <template #UserImg="{ row }">
          <div class="MyAvatar">
            <MyAvatar :userId="row.userId" :avatr="userInfo?.avatar"></MyAvatar>
          </div>
        </template>
        <template #status="{ row }">
          <div>{{ row.status === 1 ? "启用" : "禁用" }}</div>
        </template>
        <template #operate="{ row }">
          <div class="operate">
            <el-button type="primary" @click="handleEdit(row)">{{
              row.status === 1 ? "禁用" : "启用"
            }}</el-button>
            <el-button type="primary" @click="allocateSpace(row)"
              >分配空间</el-button
            >
          </div>
        </template>
        <template #UserSpaceuse="{ row }">
          <div>
            {{ formatBytes(row.useSpace) }} /
            {{ formatBytes(row.totalSpace) }}
          </div>
        </template>
      </MyTable>
    </div>
  </div>
</template>
  
  <script setup>
import {
  ref,
  reactive,
  getCurrentInstance,
  nextTick,
  onMounted,
  onUnmounted,
  h,
} from "vue";
import formatBytes from "@/utils/bit.js";
import { ar } from "element-plus/es/locales.mjs";
const { proxy } = getCurrentInstance();
import { ElInput, ElSelect, ElOption, ElSlider } from "element-plus";
const api = {
  loadUserList: "/admin/loadUserList",
  updateUserStatus: "/admin/updateUserStatus",
  updateUserSpace: "/admin/updateUserSpace",
};
const unitMap = {
  1: 1, // MB -> MB
  2: 1024, // GB -> MB
  3: 1048576, // TB -> MB (1024 * 1024)
};
const convertToMB = (value, unit) => {
  return value * unitMap[unit];
};

const formData = ref({
  nickNameFuzzy: "",
  Userstatus: "",
});
const selectListfiles = ref([]);
const formDataRef = ref();
const rules = {
  Userstatus: [
    {
      validator: (rule, value, callback) => {
        // const nickNameFuzzy = formData.value.nickNameFuzzy;

        // if (nickNameFuzzy && !value) {
        //   // 当昵称有值但状态为空时提示
        //   callback(new Error("请选择用户状态"));
        // } else {
        //   // 其他情况验证通过
        // }
        callback();
      },
      trigger: ["blur", "change"],
    },
  ],
  nickNameFuzzy: [
    {
      validator: (rule, value, callback) => {
        // const userStatus = formData.value.Userstatus;

        // if (userStatus && !value) {
        //   // 当状态有值但昵称为空时提示
        //   callback(new Error("请输入昵称"));
        // } else {
        // }
        callback();
      },
      trigger: "blur",
    },
  ],
};

const tableRef = ref();
const tableData = ref({});
const userInfo = ref(proxy.VueCookies.get("userInfo"));

const columns = [
  {
    label: "头像",
    prop: "userId",
    width: 150,
    scopedSlots: "UserImg",
  },
  {
    label: "昵称",
    prop: "nickName",
  },
  {
    label: "邮箱",
    prop: "email",
  },
  {
    label: "空间使用情况",
    width: 300,
    scopedSlots: "UserSpaceuse",
  },
  {
    label: "加入时间",
    prop: "joinTime",
    width: 160,
  },
  {
    label: "最后登录时间",
    prop: "lastLoginTime",
    width: 160,
  },
  {
    label: "状态",
    prop: "status",
    width: 100,
    scopedSlots: "status",
  },
  {
    label: "操作",
    scopedSlots: "operate",
    width: 200,
  },
];
const tableOptions = ref({
  extHight: 50,
  showPagination: true,
});

const loadDataList = async ({ pageNo = 1, pageSize = 10, ...args } = {}) => {
  let params = {
    pageNo: tableData.value.pageNo || pageNo || 1,
    pageSize: tableData.value.pageSize || pageSize || 10,
  };
  if (args.nickNameFuzzy) {
    params.nickNameFuzzy = args?.nickNameFuzzy;
  }
  if (args.Userstatus) {
    params.status = args?.Userstatus;
  }
  let res = await proxy.request({
    url: api.loadUserList,
    params,
  });
  if (!res) {
    return;
  }
  tableData.value = res.data;
};

const handleSearch = () => {
  formDataRef.value.validate((valid) => {
    if (valid) {
      // 验证通过后执行搜索
      loadDataList(formData.value);
    }
  });
};

const handleEdit = (row) => {
  proxy.confirm(
    h("div", { style: "display: flex" }, [
      h("div", null, [
        `确定要${row.status === 1 ? "禁用" : "启用"}`,
        h("span", { style: "color: teal;margin:0 .5rem;" }, `${row.nickName}`),
        "吗?",
      ]),
    ]),
    async () => {
      let params = { userId: row.userId, status: row.status == 1 ? 0 : 1 };
      let result = await proxy.request({
        url: api.updateUserStatus,
        params,
      });
      if (!result) {
        return;
      }
      loadDataList(formData.value);
    }
  );
};

const allocateSpace = (row) => {
  const mbValue = ref(0);
  const selectuserSpacevalue = ref("1");
  proxy.confirm(
    () =>
      h("div", { style: "width: 300px;margin:2rem 0" }, [
        h(
          ElInput,
          {
            clearable: true,
            modelValue: mbValue.value,
            "onUpdate:modelValue": (val) => {
              mbValue.value = val;
            },
          },
          {
            append: () =>
              h(
                ElSelect,
                {
                  modelValue: selectuserSpacevalue.value,
                  placeholder: "请选择单位",
                  style: { width: "115px" },
                  "onUpdate:modelValue": (val) => {
                    selectuserSpacevalue.value = val;
                  },
                },
                [
                  h(ElOption, { value: "1", label: "MB" }, "MB"),
                  h(ElOption, { value: "2", label: "GB" }, "GB"),
                  h(ElOption, { value: "3", label: "TB" }, "TB"),
                ]
              ),
          }
        ),
        h(ElSlider, {
          modelValue: mbValue.value,
          "onUpdate:modelValue": (val) => {
            mbValue.value = val;
          },
          max: 1023,
          min: -1023,
        }),
      ]),
    async () => {
      // 提交逻辑 - 使用转换函数并验证数据
      const convertedValue = convertToMB(
        mbValue.value,
        selectuserSpacevalue.value
      );
      if (!convertedValue) {
        proxy.Mymessage.error("请输入有效的空间值");
        return;
      }
      let params = {
        userId: row.userId,
        changeSpace: convertedValue, // 使用转换后的值
      };

      let result = await proxy.request({
        url: api.updateUserSpace, // 修复错误的API地址
        params,
      });
      if (!result) return;
      loadDataList(formData.value);
    },
    "请输入有效的空间值",
    null,
    true
  );
};

defineExpose({});
</script>
  
<style scoped lang="scss">
.slider-demo-block {
  width: 400px;
  background-color: #409eff;
}
.table-header {
  margin-bottom: 20px;
  padding: 0 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}
.file-name {
  display: flex;
  align-items: center;
  justify-content: space-between;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}
.file-list {
  height: calc(100vh - 130px);
  display: flex;
  flex-direction: column;
  flex: 1 0 auto;
  .fileName {
    text-align: center;
    display: flex;
    align-items: center;
    height: 100%;
    justify-content: flex-start;
  }
  .MyAvatar {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .operate {
    display: flex;
  }
}
.fileedits {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: auto;
  flex-wrap: nowrap;
  span {
    user-select: none;
    text-align: center;
    display: flex;
    align-items: center;
    overflow-x: auto;
    margin-right: 10px;
    white-space: nowrap;
    transition: color 0.3s;
    cursor: pointer;
    &:hover {
      color: #409eff;
    }
  }
}
.edit-panle {
  display: flex;
  align-items: center;
  width: 100%;
  height: 40px;
  min-width: 250px;
}
.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background-color: rgb(255, 255, 255);
}
.header-actions {
  display: flex;
  justify-content: start;
  align-items: center;
  padding: 10px;

  .search-form {
    display: flex;
    align-items: center;
    width: 40vw;
    .select {
      width: 10vw;
    }
  }
}
.icon {
  margin-right: 5px;
}
.tips {
  margin-left: 1rem;
  a {
    color: #409eff;
  }
}
.custom-confirm-message {
  text-align: center;
  color: #409eff !important;
}
</style>
